package ldh.im.dto.codec.binery;

import io.netty.buffer.ByteBuf;
import ldh.im.dto.codec.BaseImCoder;
import ldh.im.dto.business.LoginResp;
import ldh.im.util.ByteBufHelp;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

public class LoginRecCodec extends ResultCodec<LoginResp> {

    @Override
    public void encode(LoginResp loginRec, ByteBuf byteBuf) {
        super.encode(loginRec, byteBuf);
        byteBuf.writeLong(loginRec.getUserId().longValue());
        byteBuf.writeLong(Date.from(loginRec.getServerDateTime().atZone(ZoneId.systemDefault()).toInstant()).getTime());
        ByteBufHelp.writeString(byteBuf, loginRec.getAuthToken(), BaseImCoder.utf8);
        byteBuf.writeInt(loginRec.getAuthCode());
    }

    @Override
    public void decode(LoginResp loginRec, ByteBuf byteBuf) {
        super.decode(loginRec, byteBuf);
        loginRec.setUserId(byteBuf.readLong());
        loginRec.setServerDateTime(LocalDateTime.ofInstant(Instant.ofEpochMilli(byteBuf.readLong()), ZoneId.systemDefault()));
        loginRec.setAuthToken(ByteBufHelp.readString(byteBuf, BaseImCoder.utf8));
        loginRec.setAuthCode(byteBuf.readInt());
    }

    @Override
    public LoginResp create() {
        return new LoginResp();
    }

    @Override
    public int getAuthCode() {
        return "login".hashCode();
    }

    @Override
    protected void checkEncode(LoginResp loginRec) {
        super.checkEncode(loginRec);
        if (loginRec.getServerDateTime() == null) {
            throw new RuntimeException("请对ServerDateTime赋值");
        }
        if (loginRec.getAuthToken() == null || loginRec.getAuthToken().trim().equals("")) {
            throw new RuntimeException("请对AuthToken赋值");
        }
        if (loginRec.getAuthCode() == null || loginRec.getAuthCode() == 0) {
            throw new RuntimeException("请对AuthCode赋值");
        }
    }
}
